#include <iostream>
#include <memory>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "TcpServer.hpp"
#include "Http.hpp"

using namespace socket_ns;

void Usage(std::string proc)
{
	std::cout << "Usage:\n\t" << proc << " local_port\n"
			  << std::endl;
}

std::shared_ptr<HttpResponse> Login(std::shared_ptr<HttpRequest> req)
{
    LOG(DEBUG, "=========================\n");
    std::string userdata;
    if (req->Method() == "GET")
    {
        userdata = req->Args();
    }
    else if (req->Method() == "POST")
    {
        userdata = req->Text();
    }
    else
    {
    }

    // 1. 进程间通信， 比如 pipe！ 还有环境变量！

    // 2. fork();

    // 3. exec(); python / php / java / C++

    // 处理数据了
    LOG(DEBUG, "enter data handler, data is : %s\n", userdata.c_str());
	


    auto response = Factory::BuildHttpResponse();
    response->AddStatusLine(200, "OK");
    response->AddHeader("Content-Type", "text/html");
    // response->AddHeader(HttpServer::ProveCookieWrite());
    response->AddHeader(HttpServer::ProveCookieTimeOut());
    response->AddHeader(HttpServer::ProveOtherCookie());
    response->AddHeader(HttpServer::ProvePath());


    // LOG(DEBUG, "Set-Cookie is : %s\n", req->Args().c_str());

    response->AddText("<html><h1>handler data done</h1></html>");
    LOG(DEBUG, "=========================\n");
    return response;
}

int main(int argc, char *argv[])
{
	if (argc != 2)
	{
		Usage(argv[0]);
		return 1;
	}
	uint16_t serverport = std::stoi(argv[1]);

	HttpServer httpsvr;
	httpsvr.AddHandler("/login",Login);
	http_t http_service = std::bind(&HttpServer::HandlerHttpReqeust,&httpsvr,std::placeholders::_1);
	std::unique_ptr<TcpServer> tcpsvr = std::make_unique<TcpServer>(serverport,http_service);
	tcpsvr->Loop();
	
	return 0;
}